package com.vogtec.fota.mqtt;

//import com.vogtec.service.mqtt.MqttMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * Created by TieYan on 2017/1/6.
 */
@Component
@Slf4j
public class EmqttCallBack implements MqttCallback {
	@Override
	public void connectionLost(Throwable cause) {
		//TODO
		log.error("connectionLost!!!!!!!!!!!!!!!!!!!!!! TODO");
	}

	//用于异步处理消息
	private class MyThreadFactory implements ThreadFactory {
		private long msg = 0l;

		@Override
		public Thread newThread(Runnable r) {
			if (msg == Long.MAX_VALUE) {
				msg = 0l;
			}
			return new Thread(r, "mqtt-user-Thread-" + msg++);
		}
	}

	private Executor executor = Executors.newFixedThreadPool(5, new MyThreadFactory());

	@Override
	public void messageArrived(String topic, MqttMessage message) throws Exception {
		MqttMessageHandler mqttMessageHandler = ApplicationContextProvider.getBean("mqttHandler", MqttMessageHandler.class);
		mqttMessageHandler.init(topic, message);
		executor.execute(mqttMessageHandler);
	}

	@Override
	public void deliveryComplete(IMqttDeliveryToken token) {
		log.trace("deliveryComplete");
	}
}